<template>
  <div>
    <el-form :inline="true">
      <el-form-item prop="province">
        <el-form-item>
          <v-distpicker @selected="onSearchSelected" :provinceOut="searchFactory.provinceCode" only-province>
          </v-distpicker>
        </el-form-item>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model.trim="searchFactory.code" placeholder="工厂代码"></el-input>
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model.trim="searchFactory.name" placeholder="工厂名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-dropdown @command="handleCommand">
          <el-button type="primary">导入<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <a href="/static/工厂导入模板.xlsx" download="工厂导入模板.xlsx" style="color:#5a5e66;text-decoration: none ">
              <el-dropdown-item command="handleDownload">模板下载</el-dropdown-item>
            </a>
            <el-dropdown-item command="handleImport">数据导入</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="excelExport">数据导出</el-button>
      </el-form-item>
    </el-form>

    <custom-table
      :columns='columns'
      :data="factoryList"
      :tableLoadingFlag="tableLoadingFlag"
      :operationColumn="operationColumn"
      :pagination="pagination">
    </custom-table>

    <!-- 工厂模板导入模态框 -->
    <el-dialog title="模板导入" :visible.sync="uploadVisible"
               :close-on-click-modal="false" :before-close="uploadCancel">
      <div>
        <el-form label-width="80px" ref="uploadForm" :inline="true">
          <el-form-item style="padding-left: 120px">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="myHeaders"
              name="file"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeAvatarUpload"
              multiple
              drag
              :limit="1"
              :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/>只能上传xlsx文件，且不超过10M</div>
            </el-upload>
          </el-form-item>
          <!--显示导入中错误的数据-->
          <div style="height: 200px;overflow-y: auto" v-if="hideTable">
            <custom-table
              :data="wrongDataList"
              :columns="detailColumns">
            </custom-table>
          </div>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="uploadCancel()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dialogType ==='add'? '新增工厂':'修改工厂信息'" :visible.sync="dialogVisible"
               :close-on-click-modal="false">
      <el-form :rules="factoryRules" :model="factoryDto" label-width="110px" ref="factoryForm">
        <el-form-item label="工厂类型" prop="factoryType">
          <el-radio-group v-model="factoryDto.factoryType" :disabled="dialogType !== 'add'">
            <el-radio :label="0">生产工厂</el-radio>
            <el-radio :label="1">芯片厂商</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="工厂代码" prop="code">
          <el-input v-model="factoryDto.code" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="工厂名称" prop="name">
          <el-input v-model="factoryDto.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="识别字母" prop="barCode" v-if="factoryDto.factoryType === 0">
          <el-input v-model="factoryDto.barCode" auto-complete="off"></el-input>
        </el-form-item>
        <div v-if="factoryDto.factoryType == 0 ">
          <el-form-item label="支持返厂" prop="supportReturnFactory">
            <el-radio-group v-model="factoryDto.supportReturnFactory">
              <el-radio :label="0">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="代理工厂" prop="proxyFactory" v-if="factoryDto.supportReturnFactory === 1"
                        :rules="{type:'number', required: true, message: '不能为空', trigger: 'blur' }">
            <el-select v-model="factoryDto.proxyFactory" placeholder="请选择代理工厂">
              <el-option v-for="item in supportFactoryList"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="所在地区">
          <el-row>
            <el-col :span="8" prop="provinceRule">
              <el-select v-model="factoryDto.provinceCode" clearable placeholder="请选择省份" @change="getCity()">
                <el-option
                  v-for="item in allProvince"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="8" prop="cityRule">
              <el-select v-model="factoryDto.cityCode" clearable placeholder="请选择城市" @change="getArea()">
                <el-option
                  v-for="item in allCityInfo"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="8" prop="areaRule">
              <el-select v-model="factoryDto.areaCode" clearable placeholder="请选择地区">
                <el-option
                  v-for="item in allAreaInfo"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="factoryDto.address" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="contact">
          <el-input v-model="factoryDto.contact" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="tel">
          <el-input v-model="factoryDto.tel" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="物流联系人" prop="logisticsContact">
          <el-input v-model="factoryDto.logisticsContact" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="物流联系电话" prop="logisticsTel">
          <el-input v-model="factoryDto.logisticsTel" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {apiFactoryReadExcel} from '@/api/excel/excelRead'
  import store from '@/store'
  import {
    apiGetFactoryList,
    apiGetFactoryById,
    apiSupportFactoryList,
    apiDelFactory,
    apiAddFactory,
    apiUpdFactory,
    apiExport
  } from '@/api/basic/info/factory'
  import {baseInfo} from '@/utils/fetch'
  import {apiGetCity, apiGetArea} from '@/api/dictionary'
  import {downloadExcel} from "../../../utils";

  export default {
    name: 'factory',
    components: {CustomTable},
    created () {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      this.getFactoryList(listQuery)
      this.getSupportFactoryList()
      this.getAllProvince()
    },
    data () {
      return {
        uploadUrl: baseInfo() + '/api/v1/upload',
        myHeaders: {'access_token': store.getters.token},
        // 上传文件显示
        fileList: [],
        // 文件上传路径
        importFileUrl: baseInfo() + '/api/v1/upload',
        // 文件上传参数
        upLoadData: {},
        dialogType: '',
        tableLoadingFlag: false,
        dialogVisible: false,
        hideTable: false,
        uploadVisible: false,
        supportFactoryList: [],
        wrongDataList: [],
        // 所有省份
        allProvince: [],
        // 所有城市
        allCityInfo: [],
        // 所有地区
        allAreaInfo: [],
        searchFactory: {
          code: '',
          name: '',
          provinceCode: ''
        },
        listQuery: {
          provinceCode: undefined,
          code: undefined,
          name: undefined
        },
        filePath: '',
        factoryDto: {
          factoryType: 0,
          code: undefined,
          name: undefined,
          barCode: undefined,
          proxyFactory: '',
          supportReturnFactory: 1,
          address: undefined,
          contact: undefined,
          tel: undefined,
          logisticsContact: undefined,
          logisticsTel: undefined,

          provinceCode: undefined,
          cityCode: undefined,
          areaCode: undefined,

          province: '',
          city: '',
          area: ''
        },
        factoryRules: {
          code: [
            {required: true, message: '请输入工厂代码', trigger: 'blur'},
            {max: 20, message: '长度不得超过 20 个字符', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请输入工厂名称', trigger: 'blur'},
            {max: 50, message: '长度不得超过 50 个字符', trigger: 'blur'}
          ],
          barCode: [
            {required: true, message: '请输入工厂识别字母', trigger: 'blur'},
            {max: 10, message: '长度不超过 10 个字符', trigger: 'blur'}
          ],

          address: [
            {required: true, message: '请输入工厂详细地址', trigger: 'blur'},
            {max: 255, message: '长度不超过 255 个字符', trigger: 'blur'}
          ],
          contact: [
            {required: true, message: '请输入联系人姓名', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          tel: [
            {required: true, message: '请输入联系人电话', trigger: 'blur'}
          ],
          logisticsContact: [
            {required: true, message: '请输入物流联系人', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          logisticsTel: [
            {required: true, message: '请输入物流联系人电话', trigger: 'blur'}
          ],
          provinceRule: [
            {required: true, message: '请选择省份', trigger: 'change'}
          ],
          cityRule: [
            {required: true, message: '请选择城市', trigger: 'change'}
          ],
          areaRule: [
            {required: true, message: '请选择地区', trigger: 'change'}
          ]
        },
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '工厂代码', name: 'code', width: '120', align: 'center'},
          {label: '工厂名称', name: 'name', width: '120', align: 'center'},
          {label: '识别字母', name: 'barCode', width: '80', align: 'center'},
          {label: '工厂类型', name: 'factoryType', width: '80', align: 'center'},
          {
            label: '支持返厂',
            name: 'supportReturnFactory',
            width: '80',
            align: 'center',
            formatter: this.formatSupportReturnFactory
          },
          {label: '代理工厂', name: 'proxyFactory', width: '120', align: 'center'},
          {label: '省份', name: 'province', width: '100', align: 'center'},
          {label: '城市', name: 'city', width: '100', align: 'center'},
          {label: '地区', name: 'area', width: '100', align: 'center'},
          {label: '工厂地址', name: 'address', align: 'center'}
        ],
        detailColumns: [
          {label: '错误行号', name: 'wrongRowNO', height: '40', align: 'center'},
          {label: '错误原因', name: 'reason', height: '40', align: 'center'},
          {label: '工厂代码', name: 'code', height: '40', align: 'center'},
          {label: '工厂类型', name: 'factoryType', height: '40', align: 'center'},
          {label: '工厂名称', name: 'name', height: '40', align: 'center'},
          {label: '负责人', name: 'contact', height: '40', align: 'center'},
          {label: '联系电话', name: 'tel', height: '40', align: 'center'},
          {label: '物流联系人', name: 'logisticsContact', height: '40', align: 'center'},
          {label: '物流联系电话', name: 'logisticsTel', height: '40', align: 'center'},
          {label: '省份', name: 'province', height: '40', align: 'center'},
          {label: '城市', name: 'city', height: '40', align: 'center'},
          {label: '地区', name: 'area', height: '40', align: 'center'},
          {label: '详细地址', name: 'address', height: '40', align: 'center'},
          {label: '识别字母', name: 'barCode', height: '40', align: 'center'},
          {label: '是否支持返厂', name: 'supportReturnFactory', height: '40', align: 'center'},
          {label: '代理工厂', name: 'proxyName', height: '40', align: 'center'}
        ],
        operationColumn: {
          width: '100',
          operations: [
            {name: '编辑', callback: this.handleEdit},
            {name: '删除', callback: this.handleDel}
          ]
        },
        factoryList: [],
        pagination: this.getData(this.getFactoryList)
      }
    },
    methods: {
      handleCommand (command) {
        if (command === 'handleImport') {
          this.dialogType = 'upload'
          this.uploadVisible = true
        } else if (command === 'handleDownload') {
        }
      },
      excelExport () {
        let paramsPost = {
          code: this.searchFactory.code,
          name: this.searchFactory.name,
          provinceCode: this.searchFactory.provinceCode
        }
        apiExport(paramsPost).then(response => {
          downloadExcel(response.data, '自有售后工厂信息导出表')
        }).catch(err => {
          console.log(err)
        })
      },
      uploadSuccess (response, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传文件成功!'
        })
        let filePath = response.data
        this.excelRead(filePath)
      },
      // 上传错误
      uploadError (err, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传失败，请重试!'
        })
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload (file) {
        const extension = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension) {
          this.$message({
            showClose: true,
            message: '上传模板只能是 xlsx 格式!'
          })
        }
        if (!isLt2M) {
          this.$message({
            showClose: true,
            message: '上传模板大小不能超过 10MB!'
          })
        }

        return extension && isLt2M
      },
      excelRead (filePath) {
        apiFactoryReadExcel(filePath).then(response => {
          if (response.data) {
            this.wrongDataList = response.data
            this.hideTable = true
          } else {
            this.$message({
              showClose: true,
              message: '导入执行中，请稍后',
              type: 'success'
            })
            this.hideTable = false
            this.getFactoryList({
              pageNumber: this.pagination.currentPage,
              pageSize: this.pagination.pageSize
            })
          }
          this.fileList = []
        })
      },
      uploadCancel () {
        this.uploadVisible = false
        this.wrongDataList = []
        this.fileList = []
        this.hideTable = false
        this.$refs['uploadForm'].resetFields()
      },
      getAllProvince () {
        apiGetCity().then(response => {
          this.allProvince = response.data
        })
      },
      getCity () {
        this.factoryDto.cityCode = ''
        if (this.factoryDto.provinceCode === '') {
          this.allCityInfo = []
        }
        let listQuery = {
          province: this.factoryDto.provinceCode
        }
        apiGetCity(listQuery).then(response => {
          this.allCityInfo = response.data
        })
      },
      getArea () {
        this.factoryDto.areaCode = ''
        if (this.factoryDto.cityCode === '') {
          this.allAreaInfo = []
        }
        let listQuery = {
          city: this.factoryDto.cityCode
        }
        apiGetArea(listQuery).then(response => {
          this.allAreaInfo = response.data
        })
      },
      formatSupportReturnFactory (row, column, cellValue) {
        if (cellValue === 1) {
          return '否'
        }
        return '是'
      },
      onSearchSelected (data) {             // 省市区联动回调
        this.searchFactory.provinceCode = data.province.code
      },
      getSupportFactoryList () {
        apiSupportFactoryList().then(response => {
          this.supportFactoryList = response.data
        }).catch(() => {
        })
      },
      getFactoryList (listQuery) {
        this.listLoadingFlag = true
        if (listQuery.provinceCode === undefined) {
          listQuery.provinceCode = this.searchFactory.provinceCode
        }
        if (listQuery.code === undefined) {
          listQuery.code = this.searchFactory.code
        }
        if (listQuery.name === undefined) {
          listQuery.name = this.searchFactory.name
        }
        apiGetFactoryList(listQuery).then(response => {
          this.factoryList = response.data
          this.pagination.totalPages = response.totalPages
          this.pagination.totalRecords = response.totalRecords
          this.listLoadingFlag = false
        }).catch(() => {
          this.listLoadingFlag = false
        })
      },
      handleAdd () {
        this.dialogType = 'add'
        this.dialogVisible = true
        if (this.$refs['factoryForm']) {
          this.factoryDto = {
            factoryType: 0,
            code: undefined,
            name: undefined,
            barCode: undefined,
            proxyFactory: '',
            supportReturnFactory: 1,
            address: undefined,
            contact: undefined,
            tel: undefined,
            logisticsContact: undefined,
            logisticsTel: undefined,
            provinceCode: undefined,
            cityCode: undefined,
            areaCode: undefined,
            province: undefined,
            city: undefined,
            area: undefined
          }
          this.$refs['factoryForm'].resetFields()
        }
      },
      handleEdit (row) {
        apiGetFactoryById(row.id).then(response => {
          this.factoryDto.provinceCode = response.data.provinceCode
          this.getCity()
          this.factoryDto.cityCode = response.data.cityCode
          this.getArea()
          this.factoryDto = response.data
          this.dialogType = 'edit'
          this.dialogVisible = true
        })
      },
      handleDel (row) {
        this.$confirm('确定删除该工厂?', '删除工厂', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apiDelFactory(row.id).then(() => {
            this.$message({
              showClose: true,
              type: 'success',
              message: '删除成功!'
            })
            this.getFactoryList(this.listQuery)
            this.getSupportFactoryList()
          })
        }).catch(() => {
        })
      },
      submit () {
        this.$refs.factoryForm.validate((valid) => {
          if (valid) {
            if (this.dialogType === 'add') {
              this.addSubmit()
            } else {
              this.updSubmit()
            }
          } else {
            return false
          }
        })
      },
      addSubmit () {
        apiAddFactory(this.factoryDto).then(() => {
          this.$message({
            showClose: true,
            message: '新增成功',
            type: 'success'
          })
          this.dialogVisible = false
          this.getFactoryList(this.listQuery)
          this.getSupportFactoryList()
        })
      },
      updSubmit () {
        apiUpdFactory(this.factoryDto).then(() => {
          this.$message({
            showClose: true,
            message: '更新成功',
            type: 'success'
          })
          this.dialogVisible = false
          this.getFactoryList(this.listQuery)
          this.getSupportFactoryList()
        })
      },
      cancel () {
        this.dialogVisible = false
        this.$refs['factoryForm'].resetFields()
      },
      searchData () {
        this.listQuery.provinceCode = this.searchFactory.provinceCode
        this.listQuery.code = this.searchFactory.code
        this.listQuery.name = this.searchFactory.name
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
        this.getFactoryList(this.listQuery)
      }
    }
  }
</script>
